// 引入mongoose
const mongoose = require("mongoose");
// 引入购物车模型
const { cartsModel } = require("../db/model/carts");

// 分页获取购物车数据
const get = async ({ curPage, eachPage }) => {
  curPage = ~~curPage;
  eachPage = ~~eachPage;
  const data = {
    total: 0,
    maxPage: 0,
    rows: [],
  };
  // 获取当前model映射的集合里面存在的文档总数
  data.total = await cartsModel.countDocuments();
  data.maxPage = Math.ceil(data.total / eachPage);
  // 跳过数据条数
  const skipNum = (curPage - 1) * eachPage;
  // 查询所有数据，并跳过skipnum条，查eachpage条并执行
  data.rows = await cartsModel.find().skip(skipNum).limit(eachPage).exec();
  return data;
};
//新增购物车
const createCart = async ({ detail }) => {
  const cartsModel = mongoose.model("carts");
  return await cartsModel.create({ detail });
};
//通过id获取该id对应的购物车数据
const getOneCart = async (_id) => {
  const cartsModel = mongoose.model("carts");
  return await cartsModel.findOne({ _id });
};
//通过购物车id修改购物车数据(购物车中数据的增加、删除、修改)
const changeCart = async (newData) => {
  const cartsModel = mongoose.model("carts");
  return await cartsModel.updateOne({ _id: newData._id }, newData);
};
//删除购物车(用户的账户注销后，购物车一并删除)
const delCart = async (_id) => {
  const cartsModel = mongoose.model("carts");
  return await cartsModel.deleteOne({ _id });
};
module.exports = {
  get,
  createCart,
  getOneCart,
  changeCart,
  delCart,
};
